/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package GUI;

import Flightadministration.*;
import Data.*;
import Report.Report;
import Interaction.ServerConnection;

import java.rmi.RemoteException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

/**
 *
 * @author David Ponce
 * @author Philipp Armbruster
 */
public class FlightRealizationManageDi extends JPanel {

    final Main td;
    private JPanel jp;
    public JTable table;
    public Vector<Vector> rowData;
    public Vector<String> columnNames;
    public DefaultTableModel model;
    public int currentFRId;
    final FlightRealizationEdit flre;
    public Vector<Aircraft> allAircrafts;

    /*Das AdministrationsObjekt, welches über die getConnection methode vom RMI Server geholt wird, dem "admin" objekt zugewiesen.
     *Dadurch ist eine Kommunikation zwischen GUI und Applikationsserver mittels RMI möglich*/
    final Flightadministration admin = ServerConnection.getConnection();


    // Konstruktor
    public FlightRealizationManageDi(final Main td, final FlightRealizationEdit flre) throws java.rmi.RemoteException {

        this.td = td;
        this.flre = flre;
        showFlightRealizationManageDi();
    }


    // Methoden
    public void showFlightRealizationManageDi() throws RemoteException {

        jp = new JPanel();

        //GridBagLayout
        //**********************************************************************

        GridBagLayout gbl = new GridBagLayout();
        jp.setLayout(gbl);
        jp.setBackground(Color.white);

        GridBagConstraints constraints = new GridBagConstraints();

        constraints.fill = GridBagConstraints.HORIZONTAL;   // wie Komponente Bereich füllen soll
        constraints.weightx = 1;                     // Breite
        constraints.weighty = 1;                    // Höhe
        constraints.insets = new Insets(0,0,1,1);   // Abstände definieren


        //Label
        //**********************************************************************

        JLabel headline = new JLabel("<html><h2 color=blue>Übersicht aller Flugdurchführungen am Dienstag</h2></html>");
        headline.setHorizontalAlignment(JLabel.CENTER);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.gridwidth = 3;
        jp.add(headline, constraints);


        //JTable
        //**********************************************************************

        columnNames = new Vector<String>();
        columnNames.add("ID");
        columnNames.add("Abflugtag");
        columnNames.add("Abflugdatum");
        columnNames.add("Abflugsuhrzeit");
        columnNames.add("Ankunftstag");
        columnNames.add("Ankunftsdatum");
        columnNames.add("Ankunftsuhrzeit");
        columnNames.add("Abflughafen");
        columnNames.add("Zielflughafen");
        columnNames.add("Fluglinie");

        // Vector mit nachfolgender for-Schleife mit Werten für JTable belegen
        rowData = admin.getAllFlightRealizationsOnTuesdayForTable();

        model = new DefaultTableModel(rowData, columnNames);
        table = new JTable(model) {
            public boolean isCellEditable(int x, int y) {
                return false;
            }
        };
        table.setModel(model);
        table.setAutoCreateRowSorter(true);
        table.getColumnModel().getColumn(0).setPreferredWidth(10);
        table.getColumnModel().getColumn(1).setPreferredWidth(50);
        table.getColumnModel().getColumn(3).setPreferredWidth(25);
        table.getColumnModel().getColumn(4).setPreferredWidth(50);
        table.getColumnModel().getColumn(6).setPreferredWidth(25);
        constraints.gridx = 0;
        constraints.gridy = 2;
        constraints.gridwidth = 3;
        table.setPreferredScrollableViewportSize(new Dimension(550,480));
        table.setVisible(true);
        jp.add( new JScrollPane(table), constraints);


        //Buttons
        //**********************************************************************

        JButton button_createFlightRealization = new JButton("Anlegen");
        constraints.gridwidth = 1;
        constraints.gridx = 0;
        constraints.gridy = 3;
        jp.add(button_createFlightRealization, constraints);

        JButton button_EditFlightRealization = new JButton("Editieren");
        constraints.gridx = 1;
        constraints.gridy = 3;
        jp.add(button_EditFlightRealization, constraints);

        JButton button_DeleteFlightRealization = new JButton("Löschen");
        constraints.gridx = 2;
        constraints.gridy = 3;
        jp.add(button_DeleteFlightRealization, constraints);


        //ActionListener
        //**********************************************************************
        table.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent evt){

                //Nur auf Doppelklick der linken Mousetaste reagieren.
                if(evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() > 1){
                    edit();
                }
            }
        });

        button_createFlightRealization.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){
                ((CardLayout) td.rightp.getLayout()).show(td.rightp, "OverviewFlightsDi");
            }
        });


        button_EditFlightRealization.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){
                if (table.getSelectedRow()==-1) {
                    JOptionPane.showMessageDialog(null, "Bitte ein Element der Liste auswählen!");
                }
                else {
                    edit();
//                    int iSelectedRow = table.getSelectedRow();
//                    Object currentFRIdasObject = table.getModel().getValueAt(iSelectedRow, 0);
//                           String currentFRIdAsString = String.valueOf(currentFRIdasObject);
//                                currentFRId = Integer.parseInt(currentFRIdAsString);
//
//                    try {
//                        FlightRealization f = admin.getFlightRealizationById(currentFRId);
//
//                        String id = String.valueOf(f.getRealizationId());
//                        String flightId = String.valueOf(f.getRelatedFlightId());
//                        String departureTime = (String) table.getModel().getValueAt(iSelectedRow, 3);
//                        String arrivalTime = (String) table.getModel().getValueAt(iSelectedRow, 6);
//                        String departureAirport = (String) table.getModel().getValueAt(iSelectedRow, 7);
//                        String arrivalAirport = (String) table.getModel().getValueAt(iSelectedRow, 8);
//                        String airline = (String) table.getModel().getValueAt(iSelectedRow, 9);
//                        String weekday = (String) table.getModel().getValueAt(iSelectedRow, 1);
//                        int idOfAircraft = f.getIdOfRelatedAircraft();
//                        // Alle Flugzeuge aus der Datenbank auslesen
//                        allAircrafts = admin.getAllAircraftsForComboBox();
//                        String aircraftName = "";
//                        // Bezeichnung des Flugzeuges auf Grundlage der Id auslesen
//                        for(int i = 0; i<allAircrafts.size(); i++) {
//                            if(allAircrafts.get(i).getCraftId() == idOfAircraft) {
//                                aircraftName = allAircrafts.get(i).getCraftName();
//                            }
//                        }
//
//                        flre.label3.setText(id);
//                        flre.label23.setText(flightId);
//                        flre.label5.setText(departureTime);
//                        flre.label7.setText(arrivalTime);
//                        flre.label9.setText(departureAirport);
//                        flre.label11.setText(arrivalAirport);
//                        flre.label13.setText(airline);
//                        flre.label15.setText(weekday);
//                        flre.label19.setText(aircraftName);
//
//                        Object chosenDepartureDate = f.getDateOfDeparture();
//                        flre.datefield1.setValue(chosenDepartureDate);
//
//                        Object chosenArrivalDate = f.getDateOfArrival();
//                        flre.datefield2.setValue(chosenArrivalDate);
//
//                        ((CardLayout) td.rightp.getLayout()).show(td.rightp, "FlightRealizationE");
//
//                    } catch (RemoteException ex) {
//                        Logger.getLogger(PassengerManage.class.getName()).log(Level.SEVERE, null, ex);
//                    }

                }
            }
        });


        button_DeleteFlightRealization.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){
                if (table.getSelectedRow()==-1) {
                    JOptionPane.showMessageDialog(null, "Bitte ein Element der Liste auswählen!");
                }
                else {
                    int iSelectedRow = table.getSelectedRow();

                    Object[] options = {"Ja","Nein"};
                    String txt = "<HTML>Flugdurchführung <i><u>"
                                    + table.getModel().getValueAt(iSelectedRow, 0)
                                    + "</i></u> wirklich löschen? <br>"
                                    + "Dabei werden alle damit in Verbindung stehenden Buchungen gelöscht</html>";
                    int n = JOptionPane.showOptionDialog(td, txt, "Flugdurchführung löschen",
                    JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    options,
                    options[1]);

                    if (n == 0) {
                        try {
                            // Id der ausgewählten Flugdurchführung auslesen
                            Object currentFlightRId = table.getModel().getValueAt(iSelectedRow, 0);
                                int currentFlightRIdAsInt = Integer.parseInt(currentFlightRId.toString());
                            // Id des mit der ausgewählten Flugdurchführung in Verbindung stehenden Fluges auslesen
                            FlightRealization fR = admin.getFlightRealizationById(currentFlightRIdAsInt);
                                int currentFlightIdAsInt = fR.getRelatedFlightId();
                            // Id des Flugzeuges auslesen, welches die Flugdurchführung durchführt
                            int aircraftIdAsInt = fR.getIdOfRelatedAircraft();
                            // Abflugdatum der ausgewählten Flugdurchführung auslesen
                            Date dateOfDeparture = fR.getDateOfDeparture();
                            // Ankunftsdatum der ausgewählten Flugdurchführung auslesen
                            Date dateOfArrival = fR.getDateOfArrival();

                            // Flugdurchführungsobjekt aus der Datenbank entfernen
                            admin.deleteFlightRealization(currentFlightRIdAsInt, dateOfDeparture, dateOfArrival, currentFlightIdAsInt, aircraftIdAsInt);

                                // JTables aktualisieren
                                td.updateFlightRealization();

                            JOptionPane.showMessageDialog(null, "Flugdurchführung gelöscht");

                        } catch (RemoteException ex) {
                            Logger.getLogger(AirportManage.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        });
    }

    public void edit() {
                    int iSelectedRow = table.getSelectedRow();
                    Object currentFRIdasObject = table.getModel().getValueAt(iSelectedRow, 0);
                           String currentFRIdAsString = String.valueOf(currentFRIdasObject);
                                currentFRId = Integer.parseInt(currentFRIdAsString);

                    try {
                        FlightRealization f = admin.getFlightRealizationById(currentFRId);

                        String id = String.valueOf(f.getRealizationId());
                        String flightId = String.valueOf(f.getRelatedFlightId());
                        String departureTime = (String) table.getModel().getValueAt(iSelectedRow, 3);
                        String arrivalTime = (String) table.getModel().getValueAt(iSelectedRow, 6);
                        String departureAirport = (String) table.getModel().getValueAt(iSelectedRow, 7);
                        String arrivalAirport = (String) table.getModel().getValueAt(iSelectedRow, 8);
                        String airline = (String) table.getModel().getValueAt(iSelectedRow, 9);
                        String weekday = (String) table.getModel().getValueAt(iSelectedRow, 1);
                        int idOfAircraft = f.getIdOfRelatedAircraft();
                        // Alle Flugzeuge aus der Datenbank auslesen
                        allAircrafts = admin.getAllAircraftsForComboBox();
                        String aircraftName = "";
                        // Bezeichnung des Flugzeuges auf Grundlage der Id auslesen
                        for(int i = 0; i<allAircrafts.size(); i++) {
                            if(allAircrafts.get(i).getCraftId() == idOfAircraft) {
                                aircraftName = allAircrafts.get(i).getCraftName();
                            }
                        }

                        flre.label3.setText(id);
                        flre.label23.setText(flightId);
                        flre.label5.setText(departureTime);
                        flre.label7.setText(arrivalTime);
                        flre.label9.setText(departureAirport);
                        flre.label11.setText(arrivalAirport);
                        flre.label13.setText(airline);
                        flre.label15.setText(weekday);
                        flre.label19.setText(aircraftName);

                        Object chosenDepartureDate = f.getDateOfDeparture();
                        flre.datefield1.setValue(chosenDepartureDate);

                        Object chosenArrivalDate = f.getDateOfArrival();
                        flre.datefield2.setValue(chosenArrivalDate);

                        ((CardLayout) td.rightp.getLayout()).show(td.rightp, "FlightRealizationE");

                    } catch (RemoteException ex) {
                        Logger.getLogger(PassengerManage.class.getName()).log(Level.SEVERE, null, ex);
                    }
    }
    public void updateTableData() throws RemoteException {

        // Vector mit Daten für JTable belegen
        rowData = admin.getAllFlightRealizationsOnTuesdayForTable();

        // Tabelleninhalt wird aktualisiert
        model.setDataVector(rowData, columnNames);

    }

    
    public JPanel getJp() {
        return jp;
    }
}